<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        v-if="~accessable.indexOf('order-supplement:apply-add')"
        type="primary"
        v-waves
        icon="el-icon-plus"
        @click="handleUpdate(null)"
      >添加补录</el-button>
      <el-select v-model="params.auditStatus" :clearable="true" placeholder="请选择状态">
        <el-option v-for="(item,value) in statusMap" :key="value" :label="item" :value="value"></el-option>
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
    </div>
    <el-table
      :height="tableHeight"
      :data="dataList"
      @sort-change="sortChange"
      v-loading="listLoading"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.orderSupplementDetails">
            <el-table-column prop="goodsNo" label="商品编码" width="120"></el-table-column>
            <el-table-column prop="goodsName" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="saleCount" label="销售数量" width="120"></el-table-column>
            <el-table-column prop="salePrice" label="售价" width="120"></el-table-column>
            <el-table-column prop="_" label="销售总金额" width="120">
              <template slot-scope="scope">{{scope.row.salePrice*scope.row.saleCount|numberFormat}}</template>
            </el-table-column>
            <el-table-column prop="providerName" label="供应商" width="180"></el-table-column>
            <el-table-column prop="orderNo" label="订单号" width="250"></el-table-column>
          </el-table>
          <div
            class="workflow"
            v-if="props.row.orderSupplementAuditSteps && props.row.orderSupplementAuditSteps.length"
          >
            审核流程:
            <div>
              <table>
                <tr>
                  <th>操作</th>
                  <th>操作人</th>
                  <th>备注意见</th>
                  <th>操作时间</th>
                </tr>
                <tr v-for="(step,stepIdx) in props.row.orderSupplementAuditSteps" :key="stepIdx">
                  <td>{{step.auditStepStatus|auditStatusFilter}}</td>
                  <td>{{step.auditor||'--'}}</td>
                  <td>{{step.auditorAdvize||'--'}}</td>
                  <td>{{step.auditCreateTime|parseTime}}</td>
                </tr>
              </table>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="virtualcard" align="center" label="会员号" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.virtualcard}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="receiver" align="center" label="收货人" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.receiver}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="telephone" align="center" label="手机号码" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.telephone}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="workdate" align="center" label="营业日期" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.workdate}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="paymentType" align="center" label="支付方式" width="120">
        <template slot-scope="scope">
          <span>{{paymentTypeFilter(scope.row.paymentType)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="收货地址" width="220">
        <template slot-scope="scope">
          <span>{{scope.row.address}}</span>
        </template>
      </el-table-column>

      <el-table-column width="180" prop="createTime" align="center" label="申请时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime|parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column width="140" prop="auditStatus" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.auditStatus | statusTagFilter"
          >{{scope.row.auditStatus|statusFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="140" prop="isSupplemented" align="center" label="补录状态">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isSupplemented?'success':'primary'"
          >{{scope.row.isSupplemented?'补录完成':'待补录'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230" class-name="small-padding">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="mini"
            v-if="~accessable.indexOf('order-supplement:submit') && (scope.row.auditStatus==0 || scope.row.auditStatus==3)"
            @click="submitSupplement(scope.row)"
          >提交</el-button>
          <el-button
            type="primary"
            size="mini"
            v-if="~accessable.indexOf('order-supplement:edit') && (scope.row.auditStatus==0 || scope.row.auditStatus==3)"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="~accessable.indexOf('order-supplement:cancel') && (scope.row.auditStatus==0 || scope.row.auditStatus==3)"
            size="mini"
            type="danger"
            @click="cancelSupplement(scope.row)"
          >作废</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules"
        ref="dataForm"
        class="dialog-form"
        :model="temp"
        label-position="left"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="会员号" prop="virtualcard">
              <el-input v-model="temp.virtualcard" placeholder="会员号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货人" prop="receiver">
              <el-input v-model="temp.receiver" placeholder="收货人"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentType">
              <el-select v-model="temp.paymentType" placeholder="请选择支付方式">
                <el-option
                  v-for="(item,index) in paymentTypes"
                  :key="index"
                  :label="item.title"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="telephone">
              <el-input v-model="temp.telephone" placeholder="手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业日期" prop="workdate">
              <el-date-picker
                :editable="false"
                v-model="temp.workdate"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="营业日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="收货人地址" prop="address">
          <el-input v-model="temp.address" placeholder="收货人地址"></el-input>
        </el-form-item>
        <el-form-item label="补录数据" prop="orderSupplementDetails">
          <div class="clearfix">
            <div class="lcontent">
              <el-row :gutter="10">
                <el-col :span="5">商品编码</el-col>
                <el-col :span="5">商品名称</el-col>
                <el-col :span="5">销售数量</el-col>
                <el-col :span="5">销售价格</el-col>
                <el-col :span="4">供应商</el-col>
              </el-row>
            </div>
          </div>
          <div
            class="clearfix"
            v-for="(detail,idx) in temp.orderSupplementDetails"
            v-if="!detail.deleted"
            :key="idx"
          >
            <div class="lcontent">
              <el-row :gutter="10">
                <el-col :span="5">
                  <el-input v-model="detail.goodsNo" prop="goodsNo" placeholder="商品编码"/>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.goodsName" placeholder="商品名称"/>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.saleCount" placeholder="销售数量"/>
                </el-col>
                <el-col :span="5">
                  <el-input v-model="detail.salePrice" placeholder="售价"/>
                </el-col>
                <el-col :span="4">
                  <el-select v-model="detail.providerId" placeholder="请选择供应商">
                    <el-option
                      v-for="p in providers"
                      :label="p.title"
                      :value="p.value"
                      :key="p.value"
                    ></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </div>
            <div class="fr">
              <el-button
                type="danger"
                @click="deleteOrderSupplementDetail(detail,idx)"
                size="mini"
              >删除</el-button>
            </div>
          </div>
          <div class="clearfix">
            <el-button type="primary" @click="addOrderSupplementDetail" size="mini">添加补录商品</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="submiting" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.lcontent {
  margin-right: 90px;
  width: 88%;
  float: left;
}
.clearfix {
  position: relative;
  margin-bottom: 10px;
}
.clearfix::after {
  content: " ";
  display: table;
  height: 0;
  width: 0;
  clear: both;
}
.fr {
  position: absolute;
  right: 0;
  top: 0;
}
.workflow {
  padding-top: 20px;
}
.workflow table {
  border-collapse: collapse;
  margin-top: 10px;
}
.workflow th,
.workflow td {
  padding: 10px;
  border: 1px solid #eee;
}
</style>

<script>
let statusMap = ['待提交', '审核中', '审核通过', '审核不通过', '已作废']
export default {
  data () {
    const validateOrderSupplementDetails = (rule, value, callback) => {
      if (value && value.length) {
        value.every(el => {
          // goodsNo,goodsName,salePrice,saleCount
          if (!el.goodsNo || !el.goodsNo.trim()) {
            callback(new Error('商品编码不能为空'))
            return false
          }
          if (!el.goodsName || !el.goodsName.trim()) {
            callback(new Error('商品名称不能为空'))
            return false
          }
          if (!el.salePrice || !el.salePrice.toString().trim()) {
            callback(new Error('销售价格不能为空'))
            return false
          }
          if (isNaN(el.salePrice)) {
            callback(new Error('销售价格必须为正确的数字'))
            return false
          }
          if (isNaN(el.providerId)) {
            callback(new Error('请选择供应商'))
            return false
          }
          if (!el.saleCount || !el.saleCount.toString().trim()) {
            callback(new Error('销售数量不能为空'))
            return false
          }
          if (!/^\d+$/.test(el.saleCount)) {
            callback(new Error('销售数量必须为整数'))
            return false
          }
          return true
        })
        callback()
      } else {
        callback()
      }
    }
    return {
      tableHeight: 0,
      statusMap: statusMap,
      paymentTypes: [],
      total: 0,
      dataList: [],
      providers: [],
      listLoading: false,
      temp: {
        id: '',
        workdate: '',
        paymentType: '',
        virtualcard: '',
        orderSupplementDetails: [],
        receiver: '',
        address: '',
        telephone: ''
      },
      rules: {
        virtualcard: [
          {
            required: true,
            message: '会员号不能为空',
            trigger: 'change'
          }
        ],
        paymentType: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ],
        receiver: [
          {
            required: true,
            message: '收货人不能为空',
            trigger: 'change'
          }
        ],
        telephone: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'change'
          }
        ],
        workdate: [
          {
            required: true,
            message: '营业日期不能为空',
            trigger: 'change'
          }
        ],
        address: [
          {
            required: true,
            message: '收货人地址不能为空',
            trigger: 'change'
          }
        ],
        orderSupplementDetails: [
          {
            required: true,
            message: '补录数据不能为空',
            trigger: 'array'
          },
          {
            validator: validateOrderSupplementDetails,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.tableHeight = window.innerHeight - 300
    this.loadPaymentTypes()
    this.loadData()
    this.loadProviders()
  },
  filters: {
    auditStatusFilter (status) {
      const statusMap = ['提交', '审核通过', '审核不通过', '重新提交']
      return statusMap[parseInt(status)]
    },
    statusFilter (status) {
      return statusMap[parseInt(status)]
    },
    statusTagFilter (status) {
      // ['待提交', '审核中', '补录完成', '审核不通过', '已作废']
      status = parseInt(status)
      return ['warning', 'primary', 'success', 'danger', 'info'][status]
    }
  },
  methods: {
    loadProviders () {
      this.$get('/admin/provider/valid-providers').then(data => {
        this.providers = data
      })
    },
    paymentTypeFilter (payment) {
      if (!payment) {
        return '';
      }
      let c
      return (
        (c = this.paymentTypes.filter(el => el.value === payment)) && c[0].title
      )
    },
    cancelSupplement (row) {
      this.$$comfirm('确认作废该补录吗?', res => {
        this.$post('/admin/order-supplement/cancel-supplement', {
          id: row.id
        }).then(data => {
          this.$$notify('作废成功')
          row.auditStatus = 4
        })
      })
    },
    submitSupplement (row) {
      this.$prompt('备注（选填）', '确认提交该补录吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          this.$post('/admin/order-supplement/submit-order-supplement', {
            id: row.id,
            auditAdvize: value
          }).then(data => {
            this.$$notify('提交成功')
            this.loadData()
          })
        })
        .catch(() => {})
    },
    handleFilter () {
      this.loadData()
    },
    handleCurrentChange (page) {
      this.params.page = page
      this.loadData()
    },
    handleSizeChange (size) {
      this.params.pageSize = size
      this.loadData()
    },
    submitForm () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          const postData = Object.assign({}, this.temp)
          postData.orderSupplementDetails.forEach((el, idx) => {
            Object.keys(el).forEach(k => {
              postData['orderSupplementDetails[' + idx + '].' + k] = el[k]
            })
          })
          if (!postData.id) {
            delete postData.id
          }
          delete postData.orderSupplementDetails
          let url = '/admin/order-supplement/create-supplement';
          if (this.isEditing) {
            url = '/admin/order-supplement/modify-supplement';
          }
          this.$post(url, postData)
            .then(data => {
              this.loadData()
              this.$$notify('操作成功')
              this.dialogFormVisible = false
            })
            .finally(_ => {
              this.submiting = false
            })
        }
      })
    },
    addOrderSupplementDetail () {
      this.temp.orderSupplementDetails.push({})
    },
    deleteOrderSupplementDetail (detail, idx) {
      const id = detail.id
      if (!id) {
        this.temp.orderSupplementDetails.splice(idx, 1)
      } else {
        let cIdx = 0
        this.temp.orderSupplementDetails.forEach((el, idx) => {
          if (el.id === detail.id) {
            cIdx = idx
          }
        })
        detail.deleted = true
        this.$set(this.temp.orderSupplementDetails, cIdx, detail)
      }
    },
    loadData () {
      this.listLoading = true
      this.$post(
        '/admin/order-supplement/query-applier-supplements',
        this.params
      )
        .then(data => {
          this.total = data.total
          this.dataList = data.orderSupplements
        })
        .finally(_ => {
          this.listLoading = false
        })
    },
    __onAfterHandleEditUpdate (row) {},
    __onFormSubmit (row) {
      this.temp._roleIds = this.temp.roleIds.join(',')
    },
    exportExcel (method, options) {
      this._parseFilters()
      this._parseParams()
      return this.$model.addParam(options).query('/admin/' + method)
    },
    exportExcelFile () {
      this.exportExcel('admin_role/exportExcel', {
        title: '账户管理',
        fields: [
          {
            field: 'username',
            title: '账号名称'
          },
          {
            field: 'createTime',
            title: '创建时间'
          },
          {
            field: 'roleName',
            title: '角色'
          },
          {
            field: 'status',
            title: '状态',
            valueMap: ['正常', '冻结']
          }
        ]
      }).then(res => {
        if (res.data.errcode == 0) {
          this.openWin(res.data.info)
        } else {
          this.$error(res.data.info)
        }
      })
    },
    exportExcelAdminRole () {
      this.exportExcel('/admin_role/exportExcel_admin_role', {
        title: '账户权限',
        fields: [
          {
            field: 'username',
            title: '账号'
          },

          {
            field: 'role_name',
            title: '角色'
          },

          {
            field: 'p1_name',
            title: '一级权限'
          },

          {
            field: 'p2_name',
            title: '二级权限'
          },

          {
            field: 'p3_name',
            title: '三级权限'
          },

          {
            field: 'p4_name',
            title: '四级权限'
          }
        ]
      }).then(info => {
        this.openWin(info)
      })
    },
    loadPaymentTypes () {
      this.$post('/admin/order-supplement/payments').then(data => {
        this.paymentTypes = data
      })
    },
    handleModifyStatus (row, tag) {
      let id = row.id
      if (tag == 'unFrozen') {
        this.$post('/admin/admin/unFrozen', {
          id
        }).then(_ => {
          row.status = 0
          this.$success()
        })
      } else if (tag == 'frozen') {
        this.$post('/admin/admin/frozen', {
          id
        }).then(_ => {
          row.status = 1
          this.$success()
        })
      }
    }
  }
}
</script>
